/**
 * 招聘需求，列表页
 */
import React from 'react';
import { Form, TreeSelect, Row, Button, Icon, Spin, Empty } from 'antd';
import { connect } from 'umi';
import { history } from 'umi'
import { PageContainer } from '@/molecules';
import { Pagination } from '@/components';
import AuthComponent from '@/utils/auth/AuthComponent';
import { Company, Organization } from '@/containers';
import { useRequest } from '@/hooks';
import { eventTrack } from '@/utils/track';

import { SelectPost } from '../containers/select';
import { DemandItem } from '../containers';
import { fetchDemand } from '../service';

function List({ form, location }) {
    const { query } = location;
    const {
        pageSize = 10,
        pageNo = 1,
        dutyCode = '',
        companyCode = '',
        organizationCode = '',
        recruitStatusList = ['1', '2', '3']
    } = query;

    const { data, run, loading } = useRequest(
        () =>
            fetchDemand({
                pageNo,
                pageSize,
                dutyCode,
                companyCode,
                organizationCode,
                recruitStatusList: !Array.isArray(recruitStatusList) ? [recruitStatusList] : recruitStatusList
            }),
        {
            refreshDeps: [query]
        }
    );

    const treeData = [
        { title: '审批中', value: '1', key: '1' },
        { title: '待认领', value: '2', key: '2' },
        { title: '招聘中', value: '3', key: '3' },
        { title: '已完成', value: '4', key: '4' },
        { title: '已取消', value: '5', key: '5' }
    ];

    const handleSubmit = React.useCallback(() => {
        form.validateFields((err, values) => {
            if (!err) {
                history.push({ query: values });
            }
        });
    }, []);

    const renderList = () => {
        if (loading) {
            return (
                <Row type="flex" justify="center" style={{ padding: 32 }}>
                    <Spin />
                </Row>
            );
        }
        if (!data?.data || data?.data?.rows?.length === 0) {
            return <Empty style={{ margin: '24px 0' }} />;
        }

        return (
            <>
                <div style={{ padding: '16px 0' }}>
                    {data?.data?.rows?.map(item => (
                        <div
                            key={item.id}
                            style={{ marginBottom: 16 }}
                            onClick={() => {
                                eventTrack({
                                    eventName: 'personnel_management_recruitment_demand_list_detail_click',
                                    pageName: 'personnel_management_recruitment',
                                    eventProps: {
                                        click_context: item.dutyName
                                    }
                                });
                            }}
                        >
                            <DemandItem
                                data={item}
                                onRefresh={() => {
                                    run();
                                }}
                            />
                        </div>
                    ))}
                </div>
            </>
        );
    };

    return (
        <PageContainer>
            <Row type="flex" justify="space-between" align="middle" style={{ marginBottom: 8 }}>
                <Form layout="inline">
                    <Form.Item label="岗位">
                        {form.getFieldDecorator('dutyCode', {
                            initialValue: dutyCode || undefined
                        })(
                            <SelectPost
                                needFiltered
                                onClick={() => {
                                    eventTrack({
                                        eventName: 'personnel_management_recruitment_demand_list_post_input_click',
                                        pageName: 'personnel_management_recruitment'
                                    });
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="机构" style={{ marginRight: 8 }}>
                        {form.getFieldDecorator('companyCode', {
                            initialValue: companyCode || undefined
                        })(
                            <Company
                                placeholder="请选择行政机构"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                onClick={() => {
                                    eventTrack({
                                        eventName: 'personnel_management_recruitment_demand_list_zzjg_input_click',
                                        pageName: 'personnel_management_recruitment'
                                    });
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item>
                        {form.getFieldDecorator('organizationCode', {
                            initialValue: organizationCode || undefined
                        })(
                            <Organization
                                placeholder="请选择组织机构"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                onClick={() => {
                                    eventTrack({
                                        eventName: 'personnel_management_recruitment_demand_list_xzjg_input_click',
                                        pageName: 'personnel_management_recruitment'
                                    });
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="状态">
                        {form.getFieldDecorator('recruitStatusList', {
                            initialValue: recruitStatusList
                        })(
                            <TreeSelect
                                style={{ width: 240 }}
                                treeCheckable
                                allowClear
                                maxTagCount={1}
                                treeData={treeData}
                                treeNodeFilterProp="title"
                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                placeholder="请选择"
                                onClick={() => {
                                    eventTrack({
                                        eventName: 'personnel_management_recruitment_demand_list_status_input_click',
                                        pageName: 'personnel_management_recruitment'
                                    });
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item>
                        <Button
                            type="primary"
                            onClick={() => {
                                handleSubmit();
                                eventTrack({
                                    eventName: 'personnel_management_recruitment_demand_list_search_submit_click',
                                    pageName: 'personnel_management_recruitment',
                                    eventProps: {
                                        submit_context: JSON.stringify(form.getFieldsValue())
                                    }
                                });
                            }}
                        >
                            搜索
                        </Button>
                    </Form.Item>
                </Form>
                <AuthComponent code="office:recruitment:course:requirement:add">
                    <Button
                        type="primary"
                        htmlType="submit"
                        onClick={() => {
                            eventTrack({
                                eventName: 'personnel_management_recruitment_demand_add_click',
                                pageName: 'personnel_management_recruitment'
                            });
                            history.push({
                                pathname: '/office/personnelManagement/recruitment/demand/apply'
                            });
                        }}
                    >
                        <Icon type="plus" />
                        招聘需求
                    </Button>
                </AuthComponent>
            </Row>
            {renderList()}
            <Pagination
                current={Number(pageNo)}
                pageSize={Number(pageSize)}
                total={data?.data?.total}
                loading={loading}
                onChange={value => {
                    const { current, ...rest } = value;
                    history.push({ query: { ...query, ...rest, pageNo: current } });
                }}
            />
        </PageContainer>
    );
}

export default connect(({ user }) => ({ user: user.currentUser }))(Form.create()(List));
